<?php
/**
 * Created by PhpStorm.
 * User: yuesir
 * Date: 2017/6/4
 * Time: 上午8:02
 */

namespace app\api\validate;


use app\lib\exception\BaseException;
use app\lib\exception\ParameterException;
use think\Exception;
use think\Request;
use think\Validate;

class BaseValidate extends Validate
{
    /**
     * 检查是否满足定义的规则
     * @return bool
     * @throws BaseException
     */
    public function goCheck()
    {
        $request = Request::instance();
        $params = $request->param();

        $result = $this->batch()->check($params);
        if ( !$result) {
            $e = new ParameterException([
               'msg' => $this->error,
            ]);

            throw $e;
        }

        return true;
    }

    //验证 ID 必须是正整数
    protected function idMustBePositive($value)
    {
        if (is_numeric($value) && is_int($value + 0) && ($value + 0) > 0) {
            return true;
        } else {
            return false;
        }
    }

    /**
     * 验证 value 是否为空
     * @param $value
     * @return bool
     */
    protected function isNotEmpty($value)
    {
        if (empty($value)) return false;

        return true;
    }

    /**
     * 是否是手机号
     * @param $value
     * @return bool
     */
    protected function isMobile($value)
    {
        $rule = '^1(3|4|5|7|8)[0-9]\d{8}$^';
        $result = preg_match($rule, $value);
        if ($result) {
            return true;
        } else {
            return false;
        }
    }

    /**
     * 根据 rule 来过滤对应的传递过来的值
     * @param array $rawData
     * @return array
     * @throws Exception
     */
    public function getDataByRule(array $rawData)
    {
        if (array_key_exists('uid', $rawData) || array_key_exists('user_id', $rawData)) {
            throw new Exception('不允许更改 uid 或者 user_id');
        }

        $pureData = [];
        foreach ($this->rule as $key => $val) {
            $pureData[$key] = $rawData[$key];
        }

        return $pureData;
    }
}